/**
 * $Id: config.cpp 73 2005-12-01 21:32:12Z tito $
 *
 * FGS is the legal property of its developers, whose names are too numerous
 * to list here.  Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */ 


#include <sstream>
#include <fstream>
#include "config.h"
#include "consts.h"

#define DEFAULT_CONFIG_FILE ".fgs/fgs-proxy.conf"

// Static member declaration
Config* Config::_instance = NULL;

// Constructor
Config::Config() {
	Set("master.url", MASTER_URL);
}

// Destructor
Config::~Config() {
}

// Return an instance of Config
Config* Config::Instance() {
	if (!_instance) 
		_instance = new Config();
	return _instance;
}

// Set default config file
void Config::SetDefaultConfig(const std::string& filename) {
	_config_filename = filename;
}

// Load configuration
bool Config::Load(std::string filename = "") {
	
	if (filename == "") {
		filename = getenv("HOME");
		filename += "/";
		filename += _config_filename;
	}

	std::clog << "[config] loading <" 
		<< filename << ">" 
		<< std::endl;

	std::string line, key, sep, value;
	std::ifstream file(filename.c_str(), std::ios::in);

	if (!file.is_open()) {
		std::cerr << "[config] unable to open \"" 
			<< filename << "\""
			<< std::endl;
		return false;
	}
	
	while (!file.eof()) {
		std::getline(file, line);
		
		if (line.empty())
			continue;
		
		std::istringstream iss(line);
		iss >> key >> sep >> value;
		
		if (key != "" && value != "") {
			std::cout << "[config] " 
				<< key << " = \"" 
				<< value << "\""
				<< std::endl;
			Set(key, value);
		}
	}

	return true;
}

